package top.easycode.app.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.easycode.app.common.BaseReq;
import top.easycode.app.common.BaseResult;
import top.easycode.app.common.BaseRsp;
import top.easycode.app.constants.RespCode;
import top.easycode.app.exception.BusinessRuntimeException;
import top.easycode.app.util.DTOUtil;
import top.easycode.app.util.ValidatorUtil;

public abstract class APPBaseService implements IBaseProcess {

    protected Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 业务处理流程
     *
     * @param context 请求报文
     * @param type    报文格式
     * @return 处理结果
     * @creation 20152015-4-16下午02:47:38
     */
    public final BaseResult process(String context, String type, String... params) {
        BaseReq req = null;
        try {
            req = parseContext(context, type);

        } catch (Exception e) {
            log.error(type + "转换" + (null != req ? req.getClass().getSimpleName() : "") + "异常");
            log.error(e.getMessage(), e);
            return new BaseResult(null, type + "转换" + (null != req ? req.getClass().getSimpleName() : "") + "异常", null);
        }

        if (req == null) {
            return new BaseResult(null, type + "解析异常", null);
        }
        //req参数校验
        ValidatorUtil.checkParameter(req);

        // 调用wsc服务
        BaseRsp rsp = callPscService(req, params);

        if (RespCode.E_0000.getCode().equals(rsp.getRespCode())) {
            // 处理返回结果
            return deParseToContext(req, rsp, type);
        } else {
            throw new BusinessRuntimeException(rsp.getRespCode(), rsp.getRespDesc());
        }
    }

    /**
     * 转换context为dto
     *
     * @param context 请求报文
     * @return 请对对象
     * @throws Exception 处理异常
     * @creation 20152015-4-16下午03:37:12
     */
    protected abstract BaseReq parseContext(String context, String type) throws Exception;


    /**
     * 调用wsc服务
     *
     * @param req
     * @return
     */
    protected abstract BaseRsp callPscService(BaseReq req, String... params);

    /**
     * 处理返回结果
     *
     * @param req
     * @param rsp
     * @param type
     * @return
     */
    private BaseResult deParseToContext(BaseReq req, BaseRsp rsp, String type) {
        // 填充context root节点属性
        try {
            String resultContext = DTOUtil.deParse(rsp, type);
            return new BaseResult(rsp.getRespCode(), rsp.getRespDesc(), resultContext);
        } catch (Exception e) {
            log.error(rsp.getClass().getSimpleName() + "转换" + type + "异常", e);
            throw new BusinessRuntimeException(RespCode.E_1011.getCode(), RespCode.E_1011.getName());
        }
    }

    public BaseRsp createRsp(RespCode respCode){
        BaseRsp rsp = new BaseRsp();
        rsp.setRespCode(respCode.getCode());
        rsp.setRespDesc(respCode.getName());
        return rsp;
    }
}
